package com.my.study.redisson.timer;

import com.my.study.redisson.constant.TaskConstants;
import com.my.study.redisson.model.ClientInfo;
import com.my.study.redisson.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 服务端心跳机制...
 * 
 * @author: yidujun
 * @create: 2021/11/08 21:03
 */
@Slf4j
@Component
public class RedisServerTimer {

    private final ScheduledExecutorService expireExecutor = new ScheduledThreadPoolExecutor(1,
            r -> new Thread(r, "ServerExpireTimer"));

    @Resource
    private RedissonClient redissonClient;


    public void doCheck() {
        expireExecutor.scheduleWithFixedDelay(() -> {
            log.info("===============服务端端心跳=============");
            try {
                RMap<String, Date> serverList = redissonClient.getMap(TaskConstants.SERVER_LIST);
                log.info("操作前服务个数:{}", serverList.size());
                for (Map.Entry<String, Date> entry : serverList.entrySet()) {
                    String key = entry.getKey();
                    Date time = entry.getValue();
                    if (time.getTime() < System.currentTimeMillis()) {
                        log.info("删除服务: [{}]", entry.getKey());
                        redissonClient.getMap(TaskConstants.SERVER_LIST).remove(entry.getKey());
                        RTopic topic = redissonClient.getTopic(TaskConstants.CHANNEL_SERVER_REST);
                        String[] split = key.split(":");
                        topic.publish(new Message("删除一个quartz实例...", new ClientInfo(split[0], split[1])));
                    } else {
                        log.info("截止时间:[{}] 大于 当前时间:[{}]，服务器编号:[{}]，未过期", time, new Date(), entry.getKey());
                    }
                }
                log.info("操作后服务个数:{}", serverList.size());
            } catch (Exception e) {
                log.error("", e);
            }
        }, 0, 4000, TimeUnit.MILLISECONDS);
    }
}
